import React from 'react';
import { Wrapper } from '@/components/wrapper';
import { PATHS_MAP, PATHS, PATH_DESCRIPTION_MAP } from '@/constants';
import { talks } from '@/data/talks/talks';
import { TalkCard } from './TalkCard';

interface Talk {
    title: string;
    event: string;
    date: string;
    link: string;
    video_url?: string;
    slides_url?: string;
    pdf_url?: string;
    description: string;
}

// 按年份分组 talks
function groupTalksByYear(talks: Talk[]) {
    const grouped = talks.reduce((acc, talk) => {
        const year = new Date(talk.date).getFullYear().toString();
        if (!acc[year]) {
            acc[year] = [];
        }
        acc[year].push(talk);
        return acc;
    }, {} as Record<string, Talk[]>);

    // 按年份降序排列
    const sortedYears = Object.keys(grouped).sort((a, b) => parseInt(b) - parseInt(a));

    // 每个年份内的 talks 按日期降序排列
    sortedYears.forEach((year) => {
        grouped[year].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    });

    return { grouped, sortedYears };
}

export default function TalksPage() {
    const { grouped, sortedYears } = groupTalksByYear(talks);

    return (
        <Wrapper className="flex flex-col px-6 pb-24 pt-8">
            <h2 className="text-3xl font-bold md:text-4xl mb-4">
                {PATHS_MAP[PATHS.SITE_TALKS]}
            </h2>
            <p className="text-muted-foreground mb-8">
                {PATH_DESCRIPTION_MAP[PATHS.SITE_TALKS] || '这里记录了我参与的演讲和分享活动～'}
            </p>

            <div className="space-y-12">
                {sortedYears.map((year, yearIndex) => (
                    <div key={year}>
                        <h3 className={`text-2xl font-bold mb-6 ${yearIndex === 0 ? '' : 'mt-10'}`}>
                            {year}
                        </h3>
                        <div className="space-y-4">
                            {grouped[year].map((talk, index) => (
                                <TalkCard key={index} talk={talk} />
                            ))}
                        </div>
                    </div>
                ))}
            </div>

            {talks.length === 0 && (
                <div className="flex flex-col items-center justify-center py-16 text-center">
                    <p className="text-muted-foreground text-lg">暂无分享记录</p>
                </div>
            )}
        </Wrapper>
    );
}
